package com.gosdk.p;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.StatFs;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.gosdk.p.vo.Offer;

public class AdClickService extends Service {

	public static Offer selectOffer;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	private String APK_DIR = Environment.getExternalStorageDirectory() + "/best_apk/";
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

        try {
            Offer offer = (Offer)intent.getSerializableExtra("offer");
            selectOffer = offer;
            String type = offer.getType();
            if (type.equals("1")) {
            	handleType1(offer);
            } else {
            	handleType2(offer);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

		
		return super.onStartCommand(intent, flags, startId);

	}
	
	private void handleType2(Offer offer) {
		String url = offer.getUrl();
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setData(Uri.parse(url));
		startActivity(i);
		
		NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		manager.cancelAll();
	}

	private void handleType1(final Offer offer) {
		boolean netSataus = false;
        boolean isWifi = false;
        ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cwjManager.getActiveNetworkInfo() != null) {
            netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
            isWifi = (cwjManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI ? true : false);
        }
        
        String localfilePath = APK_DIR + MD5Checksum.getChecksum4String(offer.getUrl()) + ".apk";

        if (!new File(APK_DIR).exists()) {
        	new File(APK_DIR).mkdirs();
        }
        
        if (new File(localfilePath).exists()) {
        	try {
				AppManager.InstallApplication(AdClickService.this, localfilePath);
				NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        		manager.cancelAll();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        } else if (!netSataus) {
            Toast.makeText(this, "Cannot access network", Toast.LENGTH_SHORT).show();
        } else if (!isWifi) {
            final Dialog dialog = new AlertDialog.Builder(this).setTitle("Kindly reminder")
                    .setMessage("Dear, suggest you download it with wifi")
                    .setPositiveButton("I don't care", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                            
                        	handleDownloadAPK(offer);
                        	
                        }
                    }).setNegativeButton("right", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        	
                        }
                    }).create();
            dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
            dialog.show();
        } else {
        	
        	handleDownloadAPK(offer);
        }
	}
	
	Handler handler = new Handler();
	
	private void handleDownloadAPK(final Offer offer){
		Toast.makeText(this, "Start downloading " + offer.getName(), Toast.LENGTH_LONG).show();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
		        double avail_sd_space = (double) stat_fs.getAvailableBlocks() * (double) stat_fs.getBlockSize();
		        // double GB_Available = (avail_sd_space / 1073741824);
		        double MB_Available = (avail_sd_space / 10485783);
		        // System.out.println("Available MB : " + MB_Available);
		        Log.d("MB", "" + MB_Available);
		        
		        final String localfilePath = APK_DIR + MD5Checksum.getChecksum4String(offer.getUrl()) + ".apk";
		        
		        try {
		            
		            FileOutputStream f = new FileOutputStream(new File(localfilePath));
		            
		            URL u = new URL(offer.getUrl());
		            HttpURLConnection c = (HttpURLConnection) u.openConnection();
		            c.setRequestMethod("GET");
		            c.setConnectTimeout(5000);
		            c.connect();
		            InputStream in = c.getInputStream();

		            byte[] buffer = new byte[1024];
		            int len1 = 0;
		            while ((len1 = in.read(buffer)) > 0) {

		                f.write(buffer, 0, len1);

		            }
		            f.close();

		            handler.post(new Runnable() {

		                @Override
		                public void run() {

		                	// download finish
		                	Toast.makeText(AdClickService.this, "Download finish" + offer.getName(), Toast.LENGTH_LONG).show();
		                	AppManager.InstallApplication(AdClickService.this, localfilePath);
		                    
		            		NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		            		manager.cancelAll();
		                }
		            });
		        } catch (Exception e) {

		            handler.post(new Runnable() {

		                @Override
		                public void run() {

		                	// download finish
		                	Toast.makeText(AdClickService.this, "Met exception " + offer.getName(), Toast.LENGTH_LONG).show();
		                }
		            });
		           
		        } finally {
		            
		        }
			}
		}).start();
	}
	
}
